package com.zd.controller;

import com.zd.entity.Comments;
import com.zd.entity.News;
import com.zd.entity.Topic;
import com.zd.service.CommentsService;
import com.zd.service.NewsService;
import com.zd.service.TopicService;
import com.zd.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
public class IndexController {


    @Autowired
    private TopicService topicService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private Environment environment;

    @GetMapping("/")
    public String Index(Model model, @RequestParam(value = "tid", required = false) Long tid) {
        List<News> newsList = null;
        if (tid == null) {
            newsList = newsService.queryAllNews();
        } else {
            newsList = newsService.queryNewsByTid(tid);
        }

        List<Topic> topics = topicService.quarryAllTopics();
        String guonei = environment.getProperty("guonei");
        String guoji = environment.getProperty("guoji");
        String yvle = environment.getProperty("yvle");
        List<News> newsList1 = newsService.queryNewsByTname(guonei);
        List<News> newsList2 = newsService.queryNewsByTname(guoji);
        List<News> newsList3 = newsService.queryNewsByTname(yvle);


        model.addAttribute("newsList", newsList);
        model.addAttribute("topics", topics);
        model.addAttribute("newsList1", newsList1);
        model.addAttribute("newsList2", newsList2);
        model.addAttribute("newsList3", newsList3);
        return "index";
    }

    @GetMapping("/index/topicnews/{tid}")
    @ResponseBody
    public Object topicNews(@PathVariable("tid") Long tid) {
        List<News> topicNewsList = newsService.queryNewsByTid(tid);
        return topicNewsList;
    }

    @GetMapping("/index/readnews/{nid}")
    public String readNews(@PathVariable("nid") Long nid, Model model) {
        News news = newsService.queryNewsByNid(nid);
        model.addAttribute("news", news);
        return "readnews";
    }

    @PostMapping("/index/addcomments")
    public String addComments(Comments comments) {
        commentsService.publishcomments(comments);
        return "redirect:/index/readnews/" + comments.getCnid();
    }

    @GetMapping("/index/pagenews")
    @ResponseBody
    public Object pageNews(@RequestParam(value = "pageNo", required = false) Integer pageNo) {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        PageUtil page = newsService.queryNewsByPage(pageNo);
        return page;
    }


}